﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;

namespace Rachmans.Sabang.Tools
{
    public static class PageHelper
    {
        static DataSourceLoader _dsLoader = null;//new DataSourceLoader();

        public static int GetJuzFromPage(int page, out quranPagesPage pg)
        {
            if (_dsLoader == null)
            {
                _dsLoader = new DataSourceLoader();
                _dsLoader.LoadJuzs();
            }

            //  Get page sura and aya.
            if (!_dsLoader.Pages.ContainsKey(page))
            {
                _dsLoader.LoadPage(page);
            }

            pg = _dsLoader.Pages[page];
            int pgSura = Int32.Parse(pg.sura);
            int pgAya = Int32.Parse(pg.aya);

            //1. Find the juz which has same sura and aya.
            quranJuzsJuz juz = _dsLoader.Juzs.Values.Where(j => Int32.Parse(j.sura) == pgSura && Int32.Parse(j.aya) == pgAya).FirstOrDefault();

            if (juz != null)
            {
                return Int32.Parse(juz.index);
            }
            else
            {
                //  2. Find the juz with the same sura BUT differen aya (even it would be good if we can get directly the aya is GREATER than the page aya.
                juz = _dsLoader.Juzs.Values.Where(j => Int32.Parse(j.sura) == pgSura && Int32.Parse(j.aya) > pgAya).FirstOrDefault();

                if (juz != null)
                {
                    return Int32.Parse(juz.index) - 1;
                }
                else
                {
                    // 3. Find the juz that has sura GREATER THAN page sura.
                    juz = _dsLoader.Juzs.Values.Where(j => Int32.Parse(j.sura) > pgSura).FirstOrDefault();

                    if (juz != null)
                    {
                        return Int32.Parse(juz.index) - 1;
                    }
                    else
                    {
                        return Constant.MAX_JUZ;
                    }
                }
            }
        }
    }
}
